package com.mgm.custom.clickdealer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mgm.base.ConverAdRoot;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.CreativeOfApp;
import com.mgm.utils.FastJsonUtils;
import com.mgm.utils.UUIDUtil;

public class ClickdealerConverToAdvertisement {
	
	//payout_type = cpe, cpa, cpi price
	public static JSONArray checkOffer(JSONArray jsonArray) {
		/**
		 * offerid,offername,trackingurl,payouttype,geo,packagename,os／platform
		 * payout
		 */
		Iterator<Object> it = jsonArray.iterator();
		while(it.hasNext()) {
			JSONObject j_obj = (JSONObject) it.next(); //ad
			String offerid = j_obj.getString("offerid");
			String offername = j_obj.getString("title");
			String trackingurl = j_obj.getString("clickurl");
			String payouttype = j_obj.getString("payout_type");
			String geo = j_obj.getString("countries"); 
			String packagename = j_obj.getString("appid");
//			String os = j_obj.getString("os"); //目前Clickdealer拉取就是Android的
			
			int v = 0;
			if(!StringUtils.isEmpty(j_obj.getString("payout")) && j_obj.getBigDecimal("payout").compareTo(BigDecimal.ZERO)==1 ) { //单价
				v = 1;
			}
			
			if(StringUtils.isEmpty(offerid) || StringUtils.isEmpty(offername) 
					|| StringUtils.isEmpty(trackingurl) || StringUtils.isEmpty(payouttype)
					|| StringUtils.isEmpty(geo) || StringUtils.isEmpty(packagename) 
					|| v==0) { //|| StringUtils.isEmpty(os) 
				it.remove();
			}
			
			/** 过滤一些数据 */
			//目前只做cpi的offer
			if(!"cpi".equalsIgnoreCase(j_obj.getString("payout_type"))) it.remove(); 
			
		}
		return jsonArray;
	}
	
	/**
	 * 
	 * @Title: toAdvertisement   
	 * @Description: 转化成我们的offer   
	 * @param: @param aderId
	 * @param: @param jsonArray
	 * @param: @return      
	 * @return: ConverAdRoot      
	 * @throws
	 */
	public static ConverAdRoot toAdvertisement(Integer aderId, JSONArray jsonArray) {
		if(jsonArray == null) {
			return null;
		}
		ConverAdRoot root = new ConverAdRoot();
		root.setAdId(aderId);
		Date curTime = new Date();
    	DateTime jodaTime = new DateTime(curTime);
    	DateTime n = jodaTime.plusHours(2);
    	
		int size = jsonArray.size(); //数组大小
		Advertisement adment = null;
		CreativeOfApp appCreativ = null;
		List<Advertisement> adlist = new ArrayList<>(size);
		Map<String, Advertisement> admap = new HashMap<>(size);
		Map<String, CreativeOfApp> camap = new HashMap<>(size);
		List<String> adIds = new ArrayList<>(size);
		List<CreativeOfApp> calist = new ArrayList<>(size);
		for (int i = 0; i < size; i++) {
			JSONObject j_obj = jsonArray.getJSONObject(i);
			JSONArray min_os_arr = j_obj.getJSONArray("include_min_os_version");
			
			//----广告===========================
			adment = new Advertisement();
//			String offerid = j_obj.getString("id")+RandomCodeUtils.randomNumeric(8); //系统生成offerid
			adment.setAdv_id(aderId); 
//			adment.setOfferId(offerid); 
			adment.setOfferName(j_obj.getString("title"));
			adment.setEnabled(true);
			
			adment.setPay_type(j_obj.getString("payout_type")); //默认cpi
			adment.setPay_price(j_obj.getBigDecimal("payout").setScale(2, BigDecimal.ROUND_DOWN)); //Clickdealer单价小数点超过两位数
			adment.setCurrency("USD"); //默认USD
			adment.setRequires(null); //不做强制
			
			adment.setOs("android");
			adment.setCountries(j_obj.getString("countries"));
			adment.setClick_url(j_obj.getString("clickurl"));
			adment.setCarrier(null);
			adment.setOs_version(null); //暂不要求
			adment.setExcitation("yes".equals(j_obj.getString("incent")) ? true : false);
    		adment.setExpire_date(n.toDate());
    		adment.setTrackingsolution(null); //检测类型Monitoring (adjust/appsflyer/mat/reyun/talkingdata)
    		adment.setKpi(j_obj.getString("restrictions"));
    		
    		adment.setCap_type(null);
    		adment.setConvernsion_cap(null);
    		adment.setDaily_conversion_cap(null);
    		adment.setMonth_conversion_cap(null);
    		adment.setPayout_cap(null);
    		adment.setDaily_payout_cap(null);
    		adment.setMonth_payout_cap(null);
    		
    		adment.setAppname(j_obj.getString("title"));
    		adment.setPkgname(j_obj.getString("appid"));
    		adment.setPreview_url(null);
    		
    		adment.setPremium(null);
    		adment.setPremium_price(null);
    		adment.setIcon(j_obj.getString("icon"));
    		adment.setStart_at(curTime);
    		adment.setEnd_at(null);
    		adment.setUpdate_time(curTime);
    		adment.setCounter(0); //默认0
    		adment.setP1(j_obj.getString("offerid")); //上游offerid
    		
    		//----商店素材======================
    		appCreativ = new CreativeOfApp();
    		appCreativ.setUid(UUIDUtil.uuidRep());
//    		appCreativ.setOfferid(offerid);
    		appCreativ.setAppname(j_obj.getString("appid"));
    		appCreativ.setCountry(j_obj.getString("countries"));
    		appCreativ.setLanguage(null);
    		appCreativ.setIconurl(j_obj.getString("icon"));
    		appCreativ.setDescription(j_obj.getString("description"));
    		appCreativ.setStoreRating(j_obj.getString("apprating"));
    		appCreativ.setUpdateTime(curTime);
    		appCreativ.setCurVersion(null);
    		if(min_os_arr!=null) {
    			appCreativ.setOsVersion(min_os_arr.getString(0));
    		}
    		appCreativ.setEnabled(true);
    		
    		adlist.add(adment);
    		admap.put(adment.getP1(), adment);
    		adIds.add(j_obj.getString("offerid"));
    		
    		calist.add(appCreativ);
    		camap.put(adment.getP1(), appCreativ);
		}
		root.setAdlist(adlist);
		root.setAdmap(admap);
		root.setAdids(adIds);
		
		root.setApplist(calist);
		root.setAppmap(camap);
		return root;
	}

	
	public static void main(String[] args) {
		String json = "{\r\n" + 
				"	\"status\": \"OK\",\r\n" + 
				"	\"ads\": [{\r\n" + 
				"		\"payout_type\": \"cpi\",\r\n" + 
				"		\"payout\": 0.13,\r\n" + 
				"		\"adtype\": \"native\",\r\n" + 
				"		\"offerid\": 35888325,\r\n" + 
				"		\"appid\": \"com.mobilebt.mathsolver\",\r\n" + 
				"		\"title\": \"Math Solver\",\r\n" + 
				"		\"description\": \"Math Solver is a very minimal but addictive game where you have random numbers and operators thrown at you and you have to put them together in a sequence that results to the given figure. It may s...\",\r\n" + 
				"		\"restrictions\": \"\",\r\n" + 
				"		\"icon\": \"http://mobair-cdnv1.akamaized.net/logo/f3b3c8c11cae12f7880138d92ae2620a618fc703.png\",\r\n" + 
				"		\"apprating\": 5.0,\r\n" + 
				"		\"appcategory\": \"Puzzle\",\r\n" + 
				"		\"incent\": \"no\",\r\n" + 
				"		\"gaid_idfa_require\": \"no\",\r\n" + 
				"		\"countries\": \"VN\",\r\n" + 
				"		\"cities\": [],\r\n" + 
				"		\"device_types\": [],\r\n" + 
				"		\"blacklist_affsub\": {\r\n" + 
				"			\"affsub1\": []\r\n" + 
				"		},\r\n" + 
				"		\"paid_action\": {\r\n" + 
				"			\"type\": \"Install\",\r\n" + 
				"			\"multiple_conversions\": false,\r\n" + 
				"			\"event_id\": 32530,\r\n" + 
				"			\"event_name\": \"Install\",\r\n" + 
				"			\"event_description\": \"Install\"\r\n" + 
				"		},\r\n" + 
				"		\"clickurl\": \"http://apptrknow.com/dir/redirect?placement_id=10219&campaign_id=35888325&affid=8732&cid=[cid]&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]&creative_id=[creative_id]\",\r\n" + 
				"		\"tracks\": {\r\n" + 
				"			\"impression\": \"http://apptrknow.com/api/v1/imp?placement_id=10219&campaign_id=35888325&p=8732\"\r\n" + 
				"		}\r\n" + 
				"	}, {\r\n" + 
				"		\"payout_type\": \"cpi\",\r\n" + 
				"		\"payout\": 0.774,\r\n" + 
				"		\"adtype\": \"native\",\r\n" + 
				"		\"offerid\": 35890042,\r\n" + 
				"		\"appid\": \"net.idt.um.android.bossrevapp\",\r\n" + 
				"		\"title\": \"BOSS Revolution®\",\r\n" + 
				"		\"description\": \"Low Cost Calling and Mobile Top-Up with Just a TapGet FREE calling time when you activate the app!Call any mobile phone in Mexico for just 1.9¢ a minute!It’s our lowest rate ever(Available only ...\",\r\n" + 
				"		\"restrictions\": \"\",\r\n" + 
				"		\"icon\": \"http://mobair-cdnv1.akamaized.net/logo/3e145af3c855d0475ea59b8ec1b1bed4155219ad.png\",\r\n" + 
				"		\"apprating\": 5.0,\r\n" + 
				"		\"appcategory\": \"Communication\",\r\n" + 
				"		\"incent\": \"no\",\r\n" + 
				"		\"gaid_idfa_require\": \"no\",\r\n" + 
				"		\"countries\": \"US\",\r\n" + 
				"		\"cities\": [],\r\n" + 
				"		\"device_types\": [],\r\n" + 
				"		\"include_min_os_version\": [\"2.3\"],\r\n" + 
				"		\"blacklist_affsub\": {\r\n" + 
				"			\"affsub1\": []\r\n" + 
				"		},\r\n" + 
				"		\"paid_action\": {\r\n" + 
				"			\"type\": \"Install\",\r\n" + 
				"			\"multiple_conversions\": false,\r\n" + 
				"			\"event_id\": 1229,\r\n" + 
				"			\"event_name\": \"Install\",\r\n" + 
				"			\"event_description\": \"Install\"\r\n" + 
				"		},\r\n" + 
				"		\"clickurl\": \"http://apptrknow.com/dir/redirect?placement_id=10219&campaign_id=35890042&affid=8732&cid=[cid]&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]&creative_id=[creative_id]\",\r\n" + 
				"		\"tracks\": {\r\n" + 
				"			\"impression\": \"http://apptrknow.com/api/v1/imp?placement_id=10219&campaign_id=35890042&p=8732\"\r\n" + 
				"		}\r\n" + 
				"	}]\r\n" + 
				"}";
		JSONObject jsonobj = FastJsonUtils.stringToJson(json);
		JSONArray jarr = jsonobj.getJSONArray("ads");
		
		JSONArray ck_jarr = checkOffer(jarr); //检查offer
		
		System.out.println(ck_jarr.size());
		ConverAdRoot root = toAdvertisement(1, ck_jarr);
		System.out.println(root.toString());
	}
}
